package com.vitabuybuy.tv.ui.home.group

import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.ext.mmkv
import com.library.common.ext.setOnclickNoRepeat
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityGroupBuyDetailBinding
import com.vitabuybuy.tv.dialog.*
import com.vitabuybuy.tv.dto.BannerDto
import com.library.common.toast.XToast
import com.library.common.util.DateUtil
import com.library.common.util.MMKVContancts
import com.tencent.imsdk.TIMConversationType
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo
import com.vitabuybuy.tv.adaptebinding.ImageAdapter
import com.vitabuybuy.tv.ui.cart.ConfirmOrderActivity
import com.vitabuybuy.tv.ui.home.group.adapter.MemberListAdapter
import com.vitabuybuy.tv.ui.home.group.viewmodel.GroupBuyZoneViewModel
import com.vitabuybuy.tv.ui.shopcenter.GoodsDetailsActivity
import com.vitabuybuy.tv.ui.shopcenter.store.StoreHomeActivity
import com.vitabuybuy.tv.ui.tencent.chat.ChatActivity
import com.vitabuybuy.tv.dialog.JoinGroupPopup
import com.vitabuybuy.tv.ui.auth.LoginActivity
import com.vitabuybuy.tv.utils.WebViewUtils
import kotlinx.android.synthetic.main.activity_group_buy_detail.*


/**
 * 作者：SimGa
 * 日期：2020/12/28
 * 时间：16:31
 * 包名：com.vitabuybuy.tv.ui.home.group
 */
class GroupBuyDetailActivity :
    BaseActivity<GroupBuyZoneViewModel, ActivityGroupBuyDetailBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = false
    override val layoutId: Int
        get() = R.layout.activity_group_buy_detail

    private var goodsId : Int?= 0
    private var scrollY = 0
    private val memberAdapter by lazy { MemberListAdapter() }
    private val specDialog by lazy { SpecSelectorDialog(mContext) }
    private val bannerlist = ArrayList<BannerDto.SlideListBean>()
    private  var hasFavDrawable: Drawable?=null
    private  var noneFavDrawable: Drawable?=null
    private var timer: CountDownTimer? = null

    override fun onGetBundle(bundle: Bundle?) {
        goodsId = bundle?.getInt("goodsId")
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.mViewModel = viewModel
        specDialog.setBottomBtn(SpecSelectorDialog.TYPE_BY_GROUP_BUY)
        initBanner()
        WebViewUtils.defaultSetting(rcvCommodityDetail)
        lvMember.apply {
            adapter = memberAdapter
            layoutManager = LinearLayoutManager(mContext)
            isNestedScrollingEnabled = false
        }

        hasFavDrawable = ContextCompat.getDrawable(mContext, R.drawable.icon_tabbar_shoucang)
        hasFavDrawable?.run {
            this.setBounds(
                0,
                0,
                this.minimumWidth,
                this.minimumHeight
            )
        }
        noneFavDrawable = ContextCompat.getDrawable(mContext, R.drawable.icon_tabbar_shoucang_n)
        noneFavDrawable?.run {
            this.setBounds(
                0,
                0,
                this.minimumWidth,
                this.minimumHeight
            )
        }
    }


    override fun observeData() {
        viewModel.getGoodsDetail(goodsId)
        viewModel.goodDetailDto.observe(this, Observer {
            viewModel.getGoodsList(it.product.id)
            for (str in it.product.images.split(";")) {
                val bannerDto = BannerDto.SlideListBean()
                bannerDto.image = str
                bannerlist.add(bannerDto)
            }
            my_banner.setBannerData(bannerlist)
            rcvCommodityDetail.loadDataWithBaseURL(
                null,
                WebViewUtils.htmlContent(it.product.description),
                "text/html",
                "UTF-8",
                null
            )
            val percent = if (it.gainQuantity == 0) {
                0.0
            } else {
                (it.salesQuantity * 1.0 / it.totalQuantity) * 100
            }
            spb_horizontal.progress = percent.toInt()

            if (it.product.isFavorites) {
                llStar.setCompoundDrawables(null, hasFavDrawable, null, null)
            } else {
                llStar.setCompoundDrawables(null, noneFavDrawable, null, null)
            }
            if (it.remainingTime == 0L) {
                tvGroupDeadline.apply {
                    setBackgroundColor(
                        ContextCompat.getColor(
                            mContext,
                            R.color.text_e0e0e0
                        )
                    )
                    text = getString(R.string.has_over)
                }
                btnPartIn.visibility = View.GONE
            } else {
                btnPartIn.visibility = View.VISIBLE
                startRemind(it.remainingTime)
                if (it.type == getString(R.string.normal_group_buy)) {
                    viewModel.getGroupBuyMember(it.product.id)
                }
            }
        })
        viewModel.memberlist.observe(this, Observer {
            val number = if (it.size > 3) 3 else it.size
            for (index in 0 until number) {
                memberAdapter.addData(it[index])
            }
        })
        viewModel.webContent.observe(this, Observer {
            GroupRulePopup(this,it.content).showPopupWindow()
        })
    }

    private fun startRemind(remainingTime: Long) {
        timer = object : CountDownTimer(remainingTime * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                tvGroupDeadline.text =
                    String.format(
                        getString(R.string.group_deadline),
                        DateUtil.formatSeconds(millisUntilFinished / 1000)
                    )
            }

            override fun onFinish() {
            }
        }
        timer?.start()
    }

    override fun eventHandling() {
        setOnclickNoRepeat(
            iv_finish, btn_share, btntvAlonePrice,
            btnPartIn, tvDetailRule, rlQuickGroup, llStar
        ){v->
            when (v) {
                iv_finish -> finish()
                btn_share -> {
                    SharePopup(this).showPopupWindow()
                }
                tvDetailRule -> {
                    viewModel.loadWebViewContet(14)
                }
                rlQuickGroup -> {
                    if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                        LoginActivity.openActivity(mContext)
                        return@setOnclickNoRepeat
                    }
                    viewModel.memberlist.value?.run {
                        if (this.size == 0) return@setOnclickNoRepeat
                        AllLimitedGroupPopup(this@GroupBuyDetailActivity, this) { bean ->
                            JoinGroupPopup(
                                mContext,
                                bean
                            ) { dto ->
                                viewModel.goodDetailDto.value?.run {
                                    specDialog.groupbuyId(dto.id)
                                    specDialog.show()
                                    specDialog.setSpecDatas(
                                        this.product.attributeList,
                                        this.product.goodsList,
                                        this.product.salePrice,
                                        if (bannerlist.isNotEmpty()) bannerlist[0].image else ""
                                    )
                                }
                            }.showPopupWindow()
                        }.showPopupWindow()
                    }
                }
                btnPartIn, btntvAlonePrice -> {
                    if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                        LoginActivity.openActivity(mContext)
                        return@setOnclickNoRepeat
                    }
                    viewModel.goodDetailDto.value?.run {
                        specDialog.setSpecDatas(
                            this.product.attributeList,
                            this.product.goodsList,
                            this.product.salePrice,
                            if (bannerlist.isNotEmpty()) bannerlist[0].image else ""
                        )
                        specDialog.groupbuyId(-1)
                        if(v == btnPartIn){
                            specDialog.groupbuyId(this.id)
                        }
                        specDialog.show()
                    }
                }
                llStar -> {
                    if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                        LoginActivity.openActivity(mContext)
                        return@setOnclickNoRepeat
                    }
                    viewModel.goodDetailDto.value?.run {
                        viewModel.collectOrcancel(
                            this.product.id,
                            this.product.isFavorites
                        )
                    }
                }
            }
        }
        scrollview.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
            this.scrollY = scrollY
            if (scrollY <= 0) {
                rl_title.setBackgroundColor(Color.argb(0, 255, 255, 255))
            } else {
                val scale = scrollY.toFloat() / rl_title!!.height
                val alpha = 255 * if (scale > 1) 1f else scale
                rl_title.setBackgroundColor(Color.argb(alpha.toInt(), 255, 255, 255))
            }
        })
        memberAdapter.setOnItemClickListener { _, item, _ ->
            if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                LoginActivity.openActivity(mContext)
                return@setOnItemClickListener
            }
            if(mmkv.decodeInt(MMKVContancts.USER_ID) == item.creator.id){
                XToast.normal(getString(R.string.you_are_join_this_group_buy))
                return@setOnItemClickListener
            }
            JoinGroupPopup(
                mContext,
                item
            ) {
                viewModel.goodDetailDto.value?.run {
                    specDialog.groupbuyId(it.id)
                    specDialog.setSpecDatas(
                        this.product.attributeList,
                        this.product.goodsList,
                        this.product.salePrice,
                        if (bannerlist.isNotEmpty()) bannerlist[0].image else ""
                    )
                    specDialog.show()
                }
            }.showPopupWindow()
        }
        specDialog.onGroupBuyClick = { goodId, groupbuyId, buyNum ->
//            if (buyNum <= viewModel.goodDetailDto.value!!.limitQuantity) {
                if (groupbuyId == -1) {
                    ConfirmOrderActivity.openActivity(
                        mContext,
                        goodId,
                        buyNum,
                        ConfirmOrderActivity.BUY_NOW
                    )
                } else {
                    ConfirmOrderActivity.openActivity(
                        mContext,
                        goodId,
                        buyNum,
                        groupbuyId,
                        if (viewModel.goodDetailDto.value?.type == getString(R.string.normal_group_buy)) {
                            if (groupbuyId == viewModel.goodDetailDto.value?.id) {
                                ConfirmOrderActivity.GROUP_BUY_CREATE
                            } else {
                                ConfirmOrderActivity.GROUP_BUY_JOIN
                            }
                        } else {
                            ConfirmOrderActivity.GROUP_BUY_BY_LIMIT_JOIN
                        }
                    )
                }
        }
        onClick({
            StoreHomeActivity.openActivity(
                mContext,
                viewModel.goodDetailDto.value?.store?.id,
                viewModel.goodDetailDto.value?.store?.name
            )
        }, btnEnterShop, llShop)
        mBinding.llCustomerService.setOnClickListener {
            if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                LoginActivity.openActivity(mContext)
                return@setOnClickListener
            }
            viewModel.goodDetailDto.value?.run {
                val chatInfo = ChatInfo()
                chatInfo.type = TIMConversationType.C2C
                chatInfo.id = this.store.id.toString()
                chatInfo.chatName = this.store.name
                ChatActivity.openActivity(mContext, chatInfo)
            }
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            0 -> {
                viewModel.getGoodsDetail(goodsId)
            }
            2 -> {
                viewModel.goodDetailDto.value?.run {
                    this.product?.let {
                       it.isFavorites = !(msg.obj as Boolean)
                        if (it.isFavorites) {
                            XToast.success(getString(R.string.already_success))
                            llStar.setCompoundDrawables(null, hasFavDrawable, null, null)
                        } else {
                            XToast.success(getString(R.string.cancel_collect))
                            llStar.setCompoundDrawables(null, noneFavDrawable, null, null)
                        }
                    }
                }
            }
            3->{
                GoodsDetailsActivity.openActivity(mContext,msg.arg1)
            }
        }
    }


    override fun onResume() {
        super.onResume()
        my_banner.startAutoPlay()
    }

    override fun onPause() {
        super.onPause()
        my_banner.stopAutoPlay()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (timer != null)
            timer?.cancel()
    }

    private fun initBanner() {
        my_banner.loadImage { _, model, view, _ ->
            ImageAdapter.setNomalImageUrl(
                view as ImageView,  (model as BannerDto.SlideListBean).image,
                ContextCompat.getDrawable(mContext, R.drawable.default_image)
            )
        }
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>, goodsId: Int) {
            mContext.startActivity(
                bundleOf(Pair("goodsId", goodsId)),
                GroupBuyDetailActivity::class.java
            )
        }
    }
}